import 'package:flutter/cupertino.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_riverpod_test/model/cart.dart';
import 'package:flutter_riverpod_test/model/product.dart';

// 刷新ChangeNotifier子类的单一属性，只影响引用该属性Widget的问题

class AppManager extends ChangeNotifier {
  /// 单例
  AppManager._internal() {
    _initial();
  }
  static final AppManager shared = AppManager._internal();
  factory AppManager() => shared;

  /// 初始化
  _initial() {
    // 初始化总商品
    for (int i=0; i<5; i++) {
      storeProducts.add(Product.randomProduct());
    }
  }

  /// 仓库总商品
  List<Product> storeProducts = [];

  /// 购物车数量
  List<Cart> carts = [];

  /// provider
  late final provider = ChangeNotifierProvider((_) => this);
  //ChangeNotifierProvider.autoDispose((_) => this);

  /// 添加商品
  addProduct() {
    storeProducts = [...storeProducts, Product.randomProduct()]; //Riverpod认为所有的State都是不可变的
    notifyListeners();
  }

  /// 刷新商品
  refreshProduct(List<Product> products) {
    storeProducts = List.from(products);
    notifyListeners();
  }

  /// 添加购物车
  addCart() {
    carts = [...carts, Cart.genCart()]; //Riverpod认为所有的State都是不可变的
    // carts.add(Cart.genCart()); //这样不会触发页面刷新
    notifyListeners();
  }

  /// 刷新购物车
  refreshCart(List<Cart> list) {
    carts = List.from(list);
    notifyListeners();
  }
}